package com.group3.assert_route;

import com.alibaba.cloud.commons.lang.StringUtils;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

@Component
public class PriceRoutePredicateFactory extends AbstractRoutePredicateFactory<PriceRoutePredicateFactory.Config>{


    public PriceRoutePredicateFactory() {
        super(Config.class);
    }

    @Override
    public Predicate<ServerWebExchange> apply(Config config) {
        return new Predicate<ServerWebExchange>() {
            @Override
            public boolean test(ServerWebExchange serverWebExchange) {
                String priceStr = serverWebExchange.getRequest().getQueryParams().getFirst("price");
                if(StringUtils.isNotEmpty(priceStr)){
                    int price = Integer.parseInt(priceStr);
                    if(price < config.getMaxPrice() && price > config.getMinPrice()){
                        return true;
                    }else {
                        return false;
                    }
                }
                return false;
            }
        };
    }
    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("minPrice","maxPrice");
    }
    @Data
    @NoArgsConstructor
    public static class Config{
        private double minPrice;
        private double maxPrice;
    }
}

